package model

import (
	"errors"
	"time"
)

type Section struct {
	Id         int64 `json:"-"`
	Duration   int32
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
	Name       string
	TotalScore int32
	EveryScore float32
	Deduct     bool
	Type       string
	Group      int32
	Qids       []int64     `json:"-"`
	Questions  []*Question `xorm:"-"`
}

func (s *Section) Some(ids []int64) ([]*Section, error) {
	var sections []*Section
	err := orm.In("id", ids).Asc("id").Find(&sections)
	return sections, err
}

func (s *Section) OneById() error {
	ok, err := orm.ID(s.Id).Get(s)
	if !ok {
		return errors.New(SectionNotFound)
	}
	return err
}

func (s *Section) Create() error {
	ok, err := orm.Insert(s)
	if ok == 0 {
		return errors.New(SectionCreateFailed)
	}
	return err
}

func (s *Section) Count() (int64, error) {
	o := orm.Where("id > ?", 0)
	if s.Deduct {
		o.And("deduct = ?", true)
	}
	return o.Count(s)
}

func (s *Section) Update() error {
	ok, err := orm.ID(s.Id).Cols("qids").Update(s)
	if ok == 0 {
		return errors.New(SectionUpdateFailed)
	}
	return err
}

func (s *Section) UpdateCols(cols ...string) error {
	ok, err := orm.ID(s.Id).Cols(cols...).Update(s)
	if ok == 0 {
		return errors.New(SectionUpdateFailed)
	}
	return err
}

func (s *Section) SomeLike(name string) ([]*Section, error) {
	var sections []*Section
	err := orm.Where("name LIKE ?", "%"+name+"%").Find(&sections)
	return sections, err
}
